<?

class Igrid_model extends CI_Model {

    private $results_per_page = 20;
    private $column_count = 0; // Num of columns
    private $row_count = 0; // Number of rows
    private $hide_header = false; // Header visibility
    private $hide_footer = false; // Footer visibility
    private $hide_order = false; // Show ordering option
    private $show_checkboxes = false; // Show checkboxes
    private $allow_filters = false; // Allow filters or not
    private $row_select = false; // Enable row selection
    private $create_button = false; // Show create button
    private $reset_button = false; // Show reset grid button
    private $show_row_number = false; // Show row numbers
    private $allow_pagesize = true; // Show row numbers
    private $hide_page_list = false; // Hide page list
    private $page = 1; // Current page
    private $primary = ''; // Tables primary key column
    private $query; // SQL query
    private $hidden = array(); // Hidden columns
    private $header = array(); // Header titles
    private $controls = array(); // Row controls, std or custom
    private $order = false; // Current order
    private $_order = false; // Current order
    private $table_key = null;
    private $filter = false; // Current filter
    private $limit = false; // Current limit
    private $_db, $result; // Database related
    private $select_fields = ''; // Field used to select
    private $select_where = ''; // Where clause
    private $select_table = ''; // Table to read
    private $image_path = ''; // Path to images
    private $table_echo = '';
    private $table_db = '';
    private $url_render  = '';
    private $delete_module = '';
    private $delete_option = array(); // เพื่อเพิ่มเงือนไข ลบ
    private $render_option = array(); // เพื่อเงือนไข การ render หน้า เช่น search 
    private $type_face = '';
    private $pagesize = array(10, 20, 30, 40);
    private $DB = null;
    private $hiddenField = array();
    
    // Filename of required images
    public $img_edit = 'edit.png';
    public $img_delete = 'delete.png';
    public $img_create = 'create.png';
    public $img_reset = 'reset.png';
    public $img_filter = 'filter.gif';
    public $img_filter_remove = 'filterremove.gif';
    public $caption = '';

    // Configuration constants

    const CUSCTRL_TEXT = 1;
    const CUSCTRL_IMAGE = 2;
    const STDCTRL_EDIT = 3;
    const STDCTRL_DELETE = 4;
    const TYPE_TEXT = 0;
    const TYPE_DATE = 1;
    const TYPE_IMAGE = 2;
    const TYPE_ONCLICK = 3;
    const TYPE_ARRAY = 4;
    const TYPE_DOLLAR = 5;
    const TYPE_HREF = 6;
    const TYPE_CHECK = 7;
    const TYPE_PERCENT = 8;
    const TYPE_CUSTOM = 9;
    const TYPE_FUNCTION = 10;
    const TYPE_NUMBER = 11;
    const TYPE_RUNNO =12;
    const ORDER_DESC = 'DESC';
    const ORDER_ASC = 'ASC';

    // Default text
    const TXT_RESET = 'Reset Table';
    const TXT_NORESULTS = 'ไม่พบข้อมูล!';

    /**
     * Constructor
     *
     * @param Eyemysql $_db The Eyesis MySQL Adapter class
     * @param string $image_path The path to datagrid images
     */
    function Igrid_model() {
        parent::Model();
        
    }

    public function __construct($image_path = '') {
        $this->DB = $this->load->database("default",TRUE);

        $this->image_path = base_url() . 'assets/css/grid/images/';

        $page = isset($_POST['page']) ? (int) $_POST['page'] : 0;
        $order = isset($_POST['$order']) ? (int) $_POST['$order'] : '';
        $filter = isset($_POST['$filter']) ? (int) $_POST['$filter'] : '';
        $size = isset($_POST['$size']) ? (int) $_POST['$size'] : $this->results_per_page;

        if (empty($page) or $page <= 0) {
            $this->setLimit(0, $this->results_per_page);
        } else { $this->page = $page; }

        $this->results_per_page = $size;

        if ($order && strlen($order) > 1) {
            list($column, $order) = $this->parseInputCond($order);
            $this->setOrder($column, $order);
        }

        if ($filter && strlen($filter) > 1) {
            list($column, $value) = $this->parseInputCond($filter);
            $this->setFilter($column, htmlentities($value, ENT_QUOTES));
        }
    }
    
    
    public function setDatabase($name){
        $this->DB = $this->load->database($name,TRUE);
        
    }
    
    public function setHiddenField($hiddenField =array()){
        $this->hiddenField = $hiddenField;
        
    }
    

    /**
     * Hides page drop down selection and replaces it with text
     *
     * @param $hide Show or hide the page drop down
     */
    public function hidePageSelectList($hide = true) {
        $this->hide_page_list = $hide;
    }

    /**
     * Allow filters
     *
     * @param boolean $allow
     */
    public function allowFilters($allow = true) {
        $this->allow_filters = $allow;
    }

    public function setUrlRender($url_render){
        $this->url_render = $url_render;
        
    }
    
    public function setDeleteModule($module,$delete_option=  array()){
        $this->delete_module = $module; 
        $this->delete_option = $delete_option;
    }
    
    
    
    public function setTypeFace($e){
        $this->type_face = $e;
        
    }
    
    /**
     * Allow filters
     *
     * @param boolean $allow
     */
    public function allowPageSize($allow = true) {
        $this->$allow_pagesize = $allow;
    }

    /**
     * Hide order functionality
     *
     * @param boolean $hide
     */
    public function hideOrder($hide = true) {
        $this->hide_order = $hide;
    }

    /**
     * Show checkboxes on each row
     *
     * @param boolean $show
     */
    public function showCheckboxes($show = true) {
        $this->show_checkboxes = $show;
    }

    /**
     * Hide header row
     *
     * @param boolean $hide
     */
    public function hideHeader($hide = true) {
        $this->hide_header = $hide;
    }

    /**
     * Hide footer row
     *
     * @param boolean $hide
     */
    public function hideFooter($hide = true) {
        $this->hide_footer = $hide;
    }

    /**
     * Show reset control
     *
     * @param string $text Display caption
     */
    public function showReset($text = self::TXT_RESET) {
        $this->reset_button = $text;
    }

    /**
     * Show row numbers
     *
     * @param boolean $show
     */
    public function showRowNumber($show = true) {
        $this->show_row_number = $show;
    }

    /**
     * Set the SELECT query
     *
     * @param string $fields Feilds to fetch from table. * for all columns
     * @param string $table Table to select from
     * @param string $primay Optional primary key column
     * @param string $where Optional where condition
     */
    public function setQuery($fields, $table, $primary = '', $where = '') {
        $this->primary = $primary;

        $this->select_fields = $fields;
        $this->select_table = $table;
        $this->select_where = $where;
    }

    /**
     * Set the SELECT query
     *
     * @param string $fields Feilds to fetch from table. * for all columns
     * @param string $table Table to select from
     * @param string $primay Optional primary key column
     * @param string $where Optional where condition
     */
    public function setQuery2($query, $primary = '', $order = '',$table_key='') {
        $this->primary = $primary;
        $this->table_key = $table_key;
        $this->query = $query;
        if ($this->order == false) {
            list($column, $order) = $this->parseInputCond($order);
            $this->setOrder($column, $order);
        }
    }

    /**
     * Set order
     *
     * @param string $column Column to apply order clause on
     * @param string $order Direction, use ORDER_* const
     */
    private function setOrder($column, $order = self::ORDER_DESC) {
        $order = ($order == self::ORDER_DESC) ? self::ORDER_DESC : self::ORDER_ASC;

        $this->order = array('Column' => $column,
            'Order' => $order);
    }

    /**
     * Set filter
     *
     * @param string $column Column to apply filter clause on
     * @param string $value Value to compare to
     */
    private function setFilter($column, $value) {
        $this->filter = array('Column' => $column,
            'Value' => $value);
    }

    /**
     * Hides a column
     *
     * @param string $column The column to be hidden
     */
    public function hideColumn($column) {
        $this->hidden[] = $column;
    }

    /**
     * Change column header caption
     *
     * @param string $column The column name
     * @param string $header The new header caption
     */
    public function setColumnHeader($column, $header, $type = self::TYPE_TEXT,
            $criteria = '', $criteria_2 = '') {
        $this->header[$column] = array($header, $type, $criteria, $criteria_2);
    }

    /**
     * Sets the maximum amount of rows per page
     *
     * @param integer $num Amount of rows per page
     */
    public function setResultsPerPage($num) {
        $this->results_per_page = (int) $num;
        $this->setLimit(0, (int) $num);
    }

    /**
     * Adds a standard control to a row
     *
     * @param integer $type The type of standard control, use STDCTRL_* const
     * @param string $action The action of the control (onclick code or href link)
     * @param integer $action_type The type of action, use TYPE_ONCLICK or TYPE_HREF
     */
    public function addStandardControl($type, $action,
            $action_type = self::TYPE_ONCLICK) {
        $action = $this->parseLinkAction($action, $action_type);

        switch ($type) {
            case self::STDCTRL_EDIT:
                $this->controls[] = '<a ' . $action . '><span class="box-edit">&nbsp;</span></a>';
                break;
            case self::STDCTRL_DELETE:
                $this->controls[] = '<a ' . $action . '><span class="box-del">&nbsp;</span></a>';
                break;
            default:
                // Invalid standard control
                break;
        }
    }

    /**
     * Adds a custom control to a row
     *
     * @param integer $type The type of custom control, use CUSCTRL_* const
     * @param string $action The action of the control (onclick code or href link)
     * @param integer $action_type The type of action, use TYPE_ONCLICK or TYPE_HREF
     * @param string $text The textual description of the control
     * @param string $image_path The location of the image if type is CUSCTRL_IMAGE
     */
    public function addCustomControl($type = self::CUSCTRL_TEXT, $action,
            $action_type = self::TYPE_ONCLICK, $text, $image_src = '') {
        $action = $this->parseLinkAction($action, $action_type);

        switch ($type) {
            case self::CUSCTRL_IMAGE:
                $this->controls[] = '<a ' . $action . '><img src="' . $image_src . '" alt="' . $text . '" title="' . $text . '" class="tbl-control-image"></a>';
                break;
            default: // Default to text
                $this->controls[] = '<a ' . $action . '>' . $text . '</a>';
                break;
        }
    }

    /**
     * Adds a create control above the table
     *
     * @param string $action The action associated to the create (onclick code or href link)
     * @param integer $action_type The type of action, use TYPE_ONCLICK or TYPE_HREF
     * @param string $text The textual description of the create
     */
    public function showCreateButton($action, $action_type = self::TYPE_ONCLICK,
            $text = 'New Record') {
        $action = $this->parseLinkAction($action, $action_type);

        $this->create_button = array('Action' => $action,
            'Text' => $text);
    }

    /**
     * Adds ability to select a entire row
     *
     * @param string $onclick The JS function to call when a row is clicked
     */
    public function addRowSelect($onclick) {
        $this->row_select = $onclick;
    }

    /**
     * Data sanitization and control for filters and ordering
     *
     * @param string $in The value to be sanitized and parsed
     */
    private function parseInputCond($in) {
        return explode(':', $in, 2);
    }

    /**
     * Replaces our variables place holders with values
     *
     * @param array $row The row associated array
     * @param string $act The string containing place holders to replace
     * @return string
     */
    private function parseVariables(array $row, $act) {
        // The only way we get an array for $act is for parameters from a column type of function
        if (is_array($act)) {
            // Loop through each passed param and replace variables where necessary
            foreach ($act as $key => $value)
                    $act[$key] = $this->parseVariables($row, $value);

            return $act;
        }

        // %_P% is an alias for the primary key, replace it with the primary key
        if ($this->primary)
                $act = str_replace('%_P%', '%' . $this->primary . '%', $act);

        preg_match_all("/%([A-Za-z0-9_ \-]*)%/", $act, $vars);

        foreach ($vars[0] as $v)
                $act = str_replace($v, $row[str_replace('%', '', $v)], $act);

        return $act;
    }

    /**
     * Builds a link action
     *
     * @param string $action The action
     * @param integer $action_type The type of actions (onclick code or href link)
     * @return string
     */
    private function parseLinkAction($action, $action_type) {
        if ($action_type == self::TYPE_ONCLICK)
                $action = 'href="javascript:;" onclick="' . $action . '"';
        else $action = 'href="' . $action . '"';

        return $action;
    }

    /**
     * Sets the limit by clause
     *
     * @param integer $low The minimum row number
     * @param integer $high The maximum row number
     */
    private function setLimit($low, $high) {
        $this->limit = array('Low' => $low,
            'High' => $high);
    }

    /**
     * Checks to see if this is an ajax table
     *
     * @return boolean
     */
    public static function isAjaxUsed() {
        if (!empty($_GET['useajax']) and $_GET['useajax'] == 'true')
                return true;

        return false;
    }

    /**
     * Creates the table header
     *
     */
    private function buildHeader() {
        //print_r( $this->result->result_array());
        // If entire header is hidden, skip all together
        if ($this->hide_header) return;

        $this->table_echo.= '<thead><tr>' . "\n";

        // Get field names of result
        //$result=  $this->result->result_array();
        //$headers=array_keys($result[0]);
        $this->column_count = count($this->header);

        // Add a blank column if the row number is to be shown
        if ($this->show_row_number) {
            $this->column_count++;
            $this->table_echo.= '<th>&nbsp;</th>' . "\n";
        }

        // Show checkboxes
        if ($this->show_checkboxes) {
            $this->column_count++;
            $this->table_echo.= '<th class=" tbl-checkall" align="center"><input type="checkbox" name="checkall"></th>' . "\n";
        }

        // Loop through each header and output it
        //print_r($this->header);
        foreach ($this->header as $key => $t) {

            // Skip column if hidden
            if (in_array($t, $this->hidden)) {
                $this->column_count--;
                continue;
            }

            // Check for header caption overrides
            //if (array_key_exists($t, $this->header))
            //	$header = $this->header[$t];
            //else
            //	$header = $t;
            if ($this->hide_order)
                    $this->table_echo.= '<th>' . $t[0] . "\n"; // Prevent the user from changing order
            else {
                if ($this->order and $this->order['Column'] == $key)
                        $order = ($this->order['Order'] == self::ORDER_ASC) ? self::ORDER_DESC
                                : self::ORDER_ASC;
                else $order = self::ORDER_ASC;
                $class = '';
                if ($this->order and $this->order['Column'] == $key)
                        $class = 'sort_' . strtolower($this->order['Order']) ;

                $this->table_echo.= '<th>
                    
<span  class="grid-header '.$class.'" >
                    
<a href="javascript:;"  onclick="tblSetOrder(\'' . $key . '\', \'' . $order . '\')">' . $t[0];

                // Show the user the order image if set
            }

            $this->table_echo.= '</span></th>' . "\n";
        }

        // If we have controls, add a blank column
        if (count($this->controls) > 0) {
            $this->column_count++;
            $this->table_echo.= '<th class=" tbl-header-action" >&nbsp;</th>' . "\n";
        }

        $this->table_echo.= '</tr></thead>' . "\n";
    }

    private function buildFilter() {
        $result = '';
        if ($this->allow_filters) {
            $result.=" column :";
            $result.=" <select id='filter-column' name='filter-column' >\n";
            $result.=" <option value=''></option>\n";
            foreach ($this->header as $key => $t) {

                // Skip column if hidden
                if (in_array($t, $this->hidden)) {
                    $this->column_count--;
                    continue;
                }
                $selected = ($key == $this->filter["Column"]) ? "selected" : "";
                $result.="<option value='" . $key . "' " . $selected . ">" . $t[0] . "</option>\n";
            }
            $result.="</select>&nbsp; <input type='text' id='filter-value' name='filter-value' value='" . $this->filter["Value"] . "' />\n";
            $result.=" <img src='" . $this->image_path . $this->img_filter . "'  class='filter' onclick='tblSetFilter()'/>\n";
            $result.=" <img src='" . $this->image_path . $this->img_filter_remove . "' class='filter' onclick='tblClearFilter()'/>\n";
        }
        return $result;
    }

    /**
     * Creates the table footer
     *
     * @param integer $shown The amounts of rows being shown in the current page
     * @param integer $first The row number of the first row
     * @param integer $last The row number of the last row
     */
    private function buildFooter($shown, $first = 0, $last = 0) {
        // Skip adding the footer if it is hidden
        if ($this->hide_footer) return;
        $pages = ceil($this->row_count / $this->results_per_page); // Total number of pages
        $this->table_echo.= '<tfoot><tr><td class="tbl-nav" colspan="' . $this->column_count . '">' . "\n";
        $this->table_echo.='<table width="100%">' . "\n" . '<tr><td width="50%" class="tbl-found">พบ <em>' . $this->row_count . '</em> รายการ';

        if ($this->row_count > 0)
                $this->table_echo.= ', รายการที่ <em>' . $first . '</em> ถึง <em>' . $last . '</em>';

        $this->table_echo.= '</td><td align="right" wdith=80%" class="tbl-pages">';

        // Handle results that span multiple pages

        if ($this->row_count > $this->results_per_page) {
            if ($this->page > 1)
                    $this->table_echo.= '<a href="javascript:;" onclick="tblSetPage(1,' . $this->results_per_page . ')"><img src="' . $this->image_path . 'arrow_first.gif" class="tbl-arrows" alt="&lt;&lt;" title="First Page"></a><a href="javascript:;" onclick="tblSetPage(' . ($this->page - 1) . ',' . $this->results_per_page . ')"><img src="' . $this->image_path . 'arrow_left.gif" class="tbl-arrows" alt="&lt;" title="Previous Page"></a>';
            else
                    $this->table_echo.= '<img src="' . $this->image_path . 'arrow_first_disabled.gif" class="tbl-arrows" alt="&lt;&lt;" title="First Page"><img src="' . $this->image_path . 'arrow_left_disabled.gif" class="tbl-arrows" alt="&lt;" title="Previous Page">';

            // Special thanks to ionut for this next few lines
            $startpage = ($this->page > 10) ? $this->page - 10 : 1;

            $endpage = (($pages - 10) > $this->page) ? $this->page + 10 : $pages;

            // Only display a portion of the selectable pages
            for ($i = $startpage; $i <= $endpage; $i++) {
                if ($i == $this->page)
                        $this->table_echo.= '&nbsp;<span class="page-selected">' . $i . '</span>&nbsp;';
                else
                        $this->table_echo.= '&nbsp;<a href="javascript:;" onclick="tblSetPage(' . $i . ',' . $this->results_per_page . ')">' . $i . '</a>&nbsp;';
            }

            if ($this->page < $pages)
                    $this->table_echo.= '<a href="javascript:;" onclick="tblSetPage(' . ($this->page + 1) . ',' . $this->results_per_page . ')"><img src="' . $this->image_path . 'arrow_right.gif" class="tbl-arrows" alt="&gt;" title="Next Page"></a><a href="javascript:;" onclick="tblSetPage(' . $pages . ',' . $this->results_per_page . ')"><img src="' . $this->image_path . 'arrow_last.gif" class="tbl-arrows" alt="&gt;&gt;" title="Last Page"></a>';
            else
                    $this->table_echo.= '<img src="' . $this->image_path . 'arrow_right_disabled.gif" class="tbl-arrows" alt="&gt;" title="Next Page"><img src="' . $this->image_path . 'arrow_last_disabled.gif" class="tbl-arrows" alt="&gt;&gt;" title="Last Page">';
        }

        $this->table_echo.= '</td><td width="0%" class="tbl-pagesize">';
        if (false) {
            // Create a selectable drop down list for pages
            $this->table_echo.= 'Page size ';
            $this->table_echo.= '<select name="tbl-page" onchange="tblSetPage(1,this.options[this.selectedIndex].value)">';
            foreach ($this->pagesize as $x) {
                $this->table_echo.= '<option value="' . $x . '"';
                if ($x == $this->results_per_page)
                        $this->table_echo.= ' selected="selected"';
                $this->table_echo.= '>' . $x . '</option>';
            }
            $this->table_echo.= '</select>';
        }


        $this->table_echo.= '</td></tr></table></td></tr></tfoot>';
    }

    /**
     * Builds row controls
     *
     * @param array $row The row associated array
     */
    private function buildControls(array $row) {
        // Add controls as needed
        if (count($this->controls) > 0) {
            $this->table_echo.= '<td class="tbl-controls">';
            foreach ($this->controls as $ctl)
                    $this->table_echo.= $this->parseVariables($row, $ctl);
            $this->table_echo.= '</td>';
        }
    }

    /**
     * Outputs the datagrid to the screen
     *
     */
    public function printTable() {
        $data = '';
        // Set the limit
        //$this->setLimit(($this->page - 1) * $this->results_per_page, $this->results_per_page);

        $total = 0;
        // FILTER
        $filter_query = '';
        if ($this->select_where)
                $filter_query .= "(" . $this->select_where . ")";

        if ($this->allow_filters and $this->filter) {
            if (!strstr($this->filter['Value'], '%'))
                    $filter_value = '%' . $this->filter['Value'] . '%';
            else $filter_value = $this->filter['Value'];

            if ($this->select_where) $filter_query = $filter_query . " AND ";

            $filter_query .= "(" . $this->filter['Column'] . " LIKE '" . $filter_value . "')";
        }
        $filter = '';
        if ($filter_query) $filter = 'WHERE ' . $filter_query;

        // ORDER
        if(isset($_POST['order'])){
            $arr = explode(":",$_POST['order']);
            
            
            $this->order['Order'] = $arr[1];
            $this->order =array('Column'=>$arr[0],'Order'=>$arr[1]);

            $this->order['Column'] = $arr[0];
            
            $order = "ORDER BY {$arr[0]} {$arr[1]}";
            
        }


        $this->row_count = count($this->DB->query($this->query)->result_array());
        $limit = ((($this->page - 1) * $this->results_per_page));
        $record = $this->row_count - $limit;
        $show = ($record >= $this->results_per_page) ? $this->results_per_page : $record;
        
        
        $query = trim($this->query);
        $query = substr($query,6);
        $offsize = ($show*$this->page)+1; 
        switch($this->DB->dbdriver){
            case'mysql':
                $sql ="  SELECT {$query} {$order} limit $limit,$record";
                break;
            case'mssql':
                $sql ="
        SELECT * FROM
        (
            SELECT TOP {$show} * FROM
            (
                SELECT TOP {$offsize} 
                {$query} ORDER BY {$this->table_key}{$this->order['Column']} ASC
            )
            AS sub ORDER BY {$this->order['Column']}  DESC
        )
        AS bar {$order}
";
                
                break;
            
        }
        
        
        
        
       
        
        
        

        $this->result = $this->DB->query($sql, false);

        if (!$this->result) {
            $this->table_echo.= '<div style="color: red; font-weight: bold; border: 2px solid red; padding: 10px;">Oops! We ran into a problem while trying to output the table. <a href="javascript:;" onclick="tblReset()">Click here</a> to reset the table or <a href="javascript:;" onclick="alert(\'' . ereg_replace('[\'"]',
                            '', $this->_db->error()) . '\')">here</a> to review the error.</div>';
            return;
        }


        $this->table_echo.= '<div id="grid">';

        $this->table_echo.= '<input type="hidden" name="page" id="page" value="' . $this->page . '">' . "\n";
        $this->table_echo.= '<input type="hidden" name="size" id="size" value="' . $this->results_per_page . '">' . "\n";
        $this->table_echo.= '<input type="hidden" name="filter" id="filter" value="' . $this->filter['Column'] . ":" . $this->filter['Value'] . '">' . "\n";
        $this->table_echo.= '<input type="hidden" name="order" id="order" value="' . $this->order['Column'] . ":" . $this->order['Order'] . '">' . "\n";
        // Output the create button
        $create = '';
        if ($this->create_button)
                $create = '<span class="tbl-create"><a ' . $this->create_button['Action'] . ' title="' . $this->create_button['Text'] . '"><img src="' . $this->image_path . $this->img_create . '" class="tbl-create-image">' . $this->create_button['Text'] . '</a></span>' . "\n";

        // Output the reset button
        if ($this->reset_button)
                $this->table_echo.= '<span class="tbl-reset"><a href="javascript:;" onclick="tblReset()" title="' . $this->reset_button . '"><img src="' . $this->image_path . $this->img_reset . '" class="tbl-reset-image">' . $this->reset_button . '</a></span>' . "\n";

        $this->table_echo.= '<div class="content-header">' . $this->buildFilter() . $create . '</div>';
        $this->table_echo.= '<table id="igrid-table" cellspacing="0" cellpadding="0" width="100%">' . "\n";

        $this->buildHeader();

        $this->table_echo.= '<tbody>';
        $i = 0; $first = 0; $last = 0;
        if ($this->row_count == 0)
                $this->table_echo.= '<tr><td colspan="' . $this->column_count . '" class="tbl-noresults">' . self::TXT_NORESULTS . '</td></tr>' . "\n";
        else {
                
            $runno = ($this->page == 0)?1:($this->page -1)*20;
            foreach ($this->result->result_array() as $row) {
                 $runno++;
                $this->table_echo.= '<tr class=" tbl-row-' . (($i % 2) ? 'odd'
                                    : 'even'); // Switch up the bgcolors on each row
                // Handle row selects
                if ($this->row_select)
                        $this->table_echo.= ' tbl-row-highlight" onclick="' . $this->parseVariables($row,
                                    $this->row_select);

                $this->table_echo.= '">';

                $line = ($this->page == 1) ? $i + 1 : $i + 1 + (($this->page - 1) * $this->results_per_page);

                $last = $line; // Last line
                if ($first == 0) $first = $line; // First line

                if ($this->show_row_number)
                        $this->table_echo.= '<td class="tbl-row-num">' . $line . '</td>' . "\n";

                if ($this->show_checkboxes)
                        $this->table_echo.= '<td align="center"  width="50"><input type="checkbox" class="tbl-checkbox" id="checkbox-' . $row[$this->primary] . '" name="tbl-checkbox[]" value="' . $row[$this->primary] . '"></td>' . "\n";

                $class = '';
                foreach ($row as $key => $value) {
                    // Skip if column is hidden
                    if (in_array($key, $this->hidden)) continue;

                    // Apply a column type to the value
                    if (array_key_exists($key, $this->header)) {
                        list($column, $type, $criteria, $criteria_2) = $this->header[$key];

                        switch ($type) {
                            case self::TYPE_TEXT:
                                break;
                            case self::TYPE_ONCLICK:
                                if ($value)
                                        $value = '<a href="javascript:;" onclick="' . $this->parseVariables($row,
                                                    $criteria) . '">' . $value . '</a>';
                                break;

                            case self::TYPE_HREF:
                                if ($value)
                                        $value = '<a href="' . $this->parseVariables($row,
                                                    $criteria) . '">' . $value . '</a>';
                                break;

                            case self::TYPE_NUMBER:
                                if ($value)
                                        $value = number_format($value, $criteria);
                                $class = " align-right";
                                break;

                            case self::TYPE_DATE:
                                if ($value) $value = get_date($value);
                                $class = " align-center";
                                break;

                            case self::TYPE_IMAGE:
                                $value = '<img src="' . $this->parseVariables($row,
                                                $criteria) . '" id="' . $key . '-' . $i . '">';
                                break;

                            case self::TYPE_ARRAY:
                                $value = $criteria[$value];
                                break;

                            case self::TYPE_CHECK:
                                if ($value == '1' or $value == 'yes' or $value == 'true' or ($criteria != '' and $value == $criteria))
                                        $value = '<img src="' . $this->image_path . 'check.gif">';
                                break;

                            case self::TYPE_PERCENT:
                                if ($criteria == true)
                                        $value *= 100; // Value is in decimal format

                                $value = round($value); // Round to the nearest decimal

                                $value .= '%';

                                // Apply a bar if an array is supplied via criteria_2
                                if (is_array($criteria_2))
                                        $value = '<div style="background: ' . $criteria_2['Back'] . '; width: ' . $value . '; color: ' . $criteria_2['Fore'] . ';">' . $value . '</div>';
                                break;

                            case self::TYPE_DOLLAR:
                                $value = '$' . number_format($value, 2);
                                $class = " align-right";
                                break;
                            case self::TYPE_CUSTOM:
                                $value = $this->parseVariables($row, $criteria);
                                break;
                            case self::TYPE_RUNNO:
                                $value = $runno;
                                break;

                            case self::TYPE_FUNCTION:
                                if (is_array($criteria_2))
                                        $value = call_user_func_array($criteria,
                                            $this->parseVariables($row,
                                                    $criteria_2));
                                else
                                        $value = call_user_func($criteria,
                                            $this->parseVariables($row,
                                                    $criteria_2));
                                break;

                            default:
                                // Invalid column type
                                break;
                        }
                        $this->table_echo.= '<td class="ls' . $class . '">' . iconv("tis-620",
                                        "utf-8", $value) . '</td>' . "\n";
                    }
                }

                $this->buildControls($row);

                $this->table_echo.= '</tr>' . "\n";

               
            }
        }

        $this->table_echo.= '</tbody>';

        $this->buildFooter($i, $first, $last);
        $js = $this->js();

        $this->table_echo.= '</table></div>'.$js;
        
        $hidden = "";
 
        foreach($this->hiddenField as $key=>$row){
            $hidden .="<input type='hidden' name='$key' value='$row'/>\r\n";
        }
        
        $output = "<form name='frm' method='post' action=''>".$this->table_echo."
            <input type='hidden' name='table_db' value='{$this->table_db}'/>
                {$hidden}
             </form>";

        return $output;
    }
    
     public function js(){
         
         $typeface ="";
         $select_all="";
         
         if($this->type_face == true){
             $typeface = " ";             
         }
         
         if($this->show_checkboxes == true){
             $select_all = "
$(document).ready(function(){
    $('input[name=checkall]').click(function(){
        if($(this).attr('checked')){
        $('input:checkbox').attr('checked',true);
        }
        else{
        $('input:checkbox').attr('checked',false);
        }
     });
});


function submitFrm(){
   if(confirm('คุณแน่ใจที่ลบรายการนี้ ?')){
      var _data = $('form[name=frm]').serialize();
      $.ajax({
		    type: 'POST',
		    url: '{$this->delete_module}',
		    data:_data,    
		    success: function(html) {
                        //alert(html);
		    	runAjax();
		    },
	 		error: function(){
          alert('error');
      }
		  }); 
            }
       
}


";
             
         }
         
         
        $delete_paramiter = $this->delete_option;
        $_data  = "";
        $data = array();
        
        foreach($delete_paramiter as $key=>$row){
            $data[] = (substr($row,0,1)!="%")?"$key:'$row'":"$key:".substr($row,1);
        }
        $_data = implode(",", $data);
        
        
        $data_render = array();
        $_data_render = '';
        foreach($this->render_option as $key=>$row){
            $data_render[] = (substr($row,0,1)!="%")?"$key:'$row'":"$key:".substr($row,1);
        }
        $_data_render = implode(",", $data_render);
        
        
        
        
         
        
        $str='
<script>
var params = ""; 
var tblpage = ""; 
var tblorder = ""; 
var tblfilter = ""; 

function tbl_search()
{	 
	 $("#form").submit();
}

function preLoading(){
               $("#preloader img").attr("src","'.  base_url().'assets/images/preload.gif")              
          }
          function preLoadingStop(){
               $("#preloader img").attr("src","'.  base_url().'assets/images/preload-stop.gif")              
          }



function tblSetPage(page,size) {
	   document.getElementById("page").value=page;
	   runAjax(); 
	}
	
function tblSetOrder(column, order) {
   tblorder = column + ":" + order; 
   $("#order").val(tblorder);
   runAjax();
}

function goURL(_url){
window.location.href=_url;
}


function tblDelete(_id) {
   if(confirm("คุณแน่ใจที่ลบรายการนี้ ?")){
	 $.ajax({
		    type: "POST",
		    url: "'.$this->delete_module.'",
		    data:{'.$_data.'},		    
		    success: function(html) {
		    //alert(html);	
                    runAjax();
		    },
	 		error: function(){
          alert("เกิดข้อผิดพลาดไม่สามารถลบข้อมูลนี้ได้.");
      }
		  });
	}
}

function runAjax()
{

preLoading();
$("#loading").ajaxStart(function(){
		$(this).show();
	});
	 $("#loading").ajaxStop(function(){
		$(this).hide();
	 });
	 $.ajax({
		    type: "POST",
		    url: "'.$this->url_render.'",
		    data:{page:$("#page").val(),order:$("#order").val(),username:$("#username").val(),firstname:$("#firstname").val()'.$_data_render.'},
		    success: function(html) {
                            
		 		$("#grid").html(html);
                                preLoadingStop();
                              '.$typeface.'
		    },
	 		error: function(){
                alert("Error loading document");
            }
		  });		  
}

$("#form").submit(function() {		 
	 runAjax();
	 return false;
});

'.$select_all.'

</script>
<style>
.tbl-pages>a{
    color:#333;
}

.box-del{
padding-left:17px;
background:url("'.$this->image_path.$this->img_delete.'") 0px 0px no-repeat;
}

.box-edit{
padding-left:17px;
background:url("'.$this->image_path.$this->img_edit.'") 0px 0px no-repeat;
}
tr.tbl-row-even:hover{
background:#e5e8eb;
}
tr.tbl-row-odd:hover{
background:#e5e8eb;
}
</style>
';
        
        return $str;
        
    }
    
    public  function setTableDB($table_db){
        $this->table_db = $table_db;
        
    }
    
    public function setRenderOption($render_option){
        $this->render_option = $render_option;
        
                
    }
    
    
    

}